import seedAgent from '@/services/seedAgent-service';
import {
  DeleteOutlined,
  EditOutlined,
  EyeOutlined,
  PlusOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  DatePicker,
  Form,
  Input,
  Modal,
  Select,
  Space,
  Table,
  Tag,
  message,
} from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import SeedAgentForm from './SeedAgentForm';

const { RangePicker } = DatePicker;
const { Option } = Select;

const SeedAgentManager: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState<any>({});
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [formMode, setFormMode] = useState<'create' | 'edit'>('create');
  const [currentRecord, setCurrentRecord] = useState<any>(null);
  const navigate = useNavigate();

  const fetchData = async (params: any = {}) => {
    setLoading(true);
    try {
      const { current, pageSize, ...filters } = params;
      const payload = {
        page: current || 1,
        per_page: pageSize || 10,
        ...filters,
      };

      const res = await seedAgent.seed_agent_list(payload);
      const response = res.data;
      setData(response.data.list);
      setPagination({
        ...pagination,
        current: response.data.page,
        pageSize: response.data.per_page,
        total: response.data.total,
      });
    } catch (error) {
      message.error('获取数据失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData({ ...pagination, ...searchParams });
  }, [pagination.current, searchParams]);

  const handleTableChange = (pagination: any) => {
    setPagination(pagination);
  };

  const handleSearch = (values: any) => {
    const params: any = {};

    if (values.purpose) params.purpose = values.purpose;
    if (values.data_source) params.data_source = values.data_source;
    if (values.knowledge_base) params.knowledge_base = values.knowledge_base;
    if (values.importance) params.importance = values.importance;
    if (values.create_date) {
      params.create_start = dayjs(values.create_date[0]).unix();
      params.create_end = dayjs(values.create_date[1]).unix();
    }

    setSearchParams(params);
    setPagination({ ...pagination, current: 1 });
  };

  const handleDelete = async (agentId: string) => {
    Modal.confirm({
      title: '确认删除此代理？',
      onOk: async () => {
        try {
          await seedAgent.seed_agent_delete({ agent_id: agentId });
          message.success('代理删除成功');
          fetchData({ ...pagination, ...searchParams });
        } catch (error) {
          message.error('删除代理失败');
          console.error(error);
        }
      },
    });
  };

  const columns = [
    {
      title: '目的',
      dataIndex: 'purpose',
      key: 'purpose',
    },
    {
      title: '数据源',
      dataIndex: 'data_source',
      key: 'data_source',
    },
    {
      title: '知识库',
      dataIndex: 'knowledge_base',
      key: 'knowledge_base',
    },
    {
      title: '重要性',
      dataIndex: 'importance',
      key: 'importance',
      render: (value: number) => (
        <Tag color={value > 7 ? 'red' : value > 5 ? 'orange' : 'green'}>
          {value}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (timestamp: number) =>
        dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button
            icon={<EyeOutlined />}
            onClick={() =>
              navigate(
                `/dataManager/seedAgentManager/seedAgentDetail/${record.agent_id}`,
              )
            }
          />
          <Button
            icon={<EditOutlined />}
            onClick={() => {
              setCurrentRecord(record);
              setFormMode('edit');
              setIsModalVisible(true);
            }}
          />
          <Button
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.agent_id)}
            danger
          />
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="种子代理管理"
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setCurrentRecord(null);
            setFormMode('create');
            setIsModalVisible(true);
          }}
        >
          创建代理
        </Button>
      }
    >
      <div style={{ marginBottom: 16 }}>
        <Form layout="inline" onFinish={handleSearch}>
          <Form.Item name="purpose">
            <Input placeholder="搜索用途" />
          </Form.Item>
          <Form.Item name="data_source">
            <Input placeholder="搜索数据源" />
          </Form.Item>
          <Form.Item name="knowledge_base">
            <Input placeholder="搜索知识库" />
          </Form.Item>
          <Form.Item name="importance">
            <Select placeholder="选择重要性" allowClear>
              {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((num) => (
                <Option key={num} value={num}>
                  {num}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="create_date">
            <RangePicker showTime />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>

      <Table
        columns={columns}
        dataSource={data}
        rowKey="agent_id"
        loading={loading}
        pagination={pagination}
        onChange={handleTableChange}
      />

      <Modal
        title={formMode === 'create' ? '创建种子代理' : '编辑种子代理'}
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <SeedAgentForm
          initialValues={currentRecord}
          mode={formMode}
          onSuccess={() => {
            setIsModalVisible(false);
            fetchData({ ...pagination, ...searchParams });
          }}
        />
      </Modal>
    </Card>
  );
};

export default SeedAgentManager;
